package com.fgba.express.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fgba.express.comm.GlobalConst;
import com.fgba.express.comm.enums.State;
import com.fgba.express.comm.exception.BizException;
import com.fgba.express.comm.result.ResultCode;
import com.fgba.express.core.controller.BaseController;
import com.fgba.express.data.dto.ExpressDto;
import com.fgba.express.data.entity.Express;
import com.fgba.express.data.entity.User;
import com.fgba.express.data.mapstruct.ExpressStruct;
import com.fgba.express.data.search.ExpressSearch;
import com.fgba.express.data.service.IExpressService;
import com.fgba.express.util.ExpressCodeGenerate;
import com.fgba.express.util.NullChecker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 快递 前端控制器
 * </p>
 *
 * @author fgba
 * @since 2022-02-24
 */
@RestController
@RequestMapping("/express")
@Api(value = "快递相关操作", tags = "快递相关操作")
public class ExpressController extends BaseController<Express, ExpressDto, ExpressSearch, IExpressService, ExpressStruct> {

    @Override
    public void createValidation(ExpressDto model) {
        if (NullChecker.isNullOrEmpty(model.getNumber())) {
            log.error("ExpressController -> save: number is null");
            throw new BizException(ResultCode.USER_REQUEST_PARAM_IS_BLANK);
        }
        if (NullChecker.isNullOrEmpty(model.getRecipient())) {
            log.error("ExpressController -> save: recipient is null");
            throw new BizException(ResultCode.USER_REQUEST_PARAM_IS_BLANK);
        }
        if (NullChecker.isNullOrZero(model.getCourierId())) {
            log.error("ExpressController -> save: courierId is null");
            throw new BizException(ResultCode.USER_REQUEST_PARAM_IS_BLANK);
        }
        if (NullChecker.isNullOrEmpty(model.getCompany())) {
            log.error("ExpressController -> save: company is null");
            throw new BizException(ResultCode.USER_REQUEST_PARAM_IS_BLANK);
        }
    }

    @Override
    public void beforeSave(Express entity) throws Exception {
        List<Express> list = service.list(Wrappers.<Express>lambdaQuery().select(Express::getCode));
        entity.setCode(ExpressCodeGenerate.getPickupCode(list.stream().map(Express::getCode).collect(Collectors.toList())));
        entity.setExpressState(false);
        entity.setInTime(LocalDateTime.now());
    }

    @Override
    public void beforeUpdate(ExpressDto model) throws Exception {
        if (model.getExpressState() != null && model.getExpressState()) {
            model.setOutTime(LocalDateTime.now());
        }
    }

    /**
     * 获取首页快递统计数据
     *
     * @return
     */
    @ApiOperation(value = "获取首页快递统计数据", notes = "获取首页快递统计数据")
    @PreAuthorize("isAuthenticated()")
    @GetMapping("/homeData")
    public Map<String, Object> getHomeData() {
        LocalDate today = LocalDate.now();
        int weekDay = today.getDayOfWeek().getValue();
        //本周的第一天
        LocalDate weekFirstDay = today.minus(weekDay, ChronoUnit.DAYS);
        Map<String, Object> data = new HashMap<>(3);
        List<Integer> inWeekData = new LinkedList<>();
        List<Integer> outWeekData = new LinkedList<>();
        int inWeekTotal = 0;
        int outWeekTotal = 0;

        for (int i = 0; i < GlobalConst.WEEK_DAY; i++) {
            //统计从周一开始，每次循环添加到下一天
            LocalDate day1 = weekFirstDay.plus(i, ChronoUnit.DAYS);
            LocalDate day2 = weekFirstDay.plus(i + 1, ChronoUnit.DAYS);
            //今天之后的数据不统计
            if (today.isBefore(day1)) {
                break;
            }
            int inNum = service.count(Wrappers.<Express>lambdaQuery().ge(Express::getInTime, day1).lt(Express::getInTime, day2));
            inWeekTotal += inNum;
            inWeekData.add(inNum);
            int outNum = service.count(Wrappers.<Express>lambdaQuery().ge(Express::getOutTime, day1).lt(Express::getOutTime, day2));
            outWeekTotal += outNum;
            outWeekData.add(outNum);
        }
        data.put("inWeekData", inWeekData);
        data.put("outWeekData", outWeekData);
        data.put("inWeekTotal", inWeekTotal);
        data.put("outWeekTotal", outWeekTotal);
        data.put("inTotal", service.count(Wrappers.<Express>lambdaQuery().eq(Express::getState, State.STATUS_AVAILABLE)));
        data.put("outTotal", service.count(Wrappers.<Express>lambdaQuery().eq(Express::getState, State.STATUS_AVAILABLE)));

        return data;
    }
}
